# Create your views here.
from django.contrib.auth import authenticate, login
from django.views import View

from model.models import Point
from server.utils import Response, Code, Request, Verify


class LoginView(View):
    """ User login view """

    @Request.getJson
    def post(self, request):
        username = request.JSON.get('username')
        password = request.JSON.get('password')
        keep = request.JSON.get('keep', 0)  #

        for code in [Verify.username(username), Verify.password(password)]:
            if code != Code.OK:
                return Response.Json(code=code)

        user = authenticate(request, username=username, password=password)
        if not user:
            return Response.Json(code=Code.Error, msg="Incorrect username or password")

        login(request, user)

        if keep:
            request.session.set_expiry(7 * 24 * 60 * 60)  # 7 days session keep login

        pointsLen = Point.objects.filter(type=Point.Type.share, uploadTime__gt=user.last_login).count()
        user.update_login_time()
        cookie = f"sessionid={request.session.session_key}"
        return Response.Json(msg="Login successful", role=user.role, sharePointUpdate=pointsLen, cookie=cookie)
